<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { showSuccessToast, showToast, type FormInstance } from 'vant'
import { loginByPassword, sendMobileCode, loginByMobile } from '@/services/user'
import { useUserStore } from '@/stores'
// 校验规则
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
// 跳转页面 useRouter 专门给 vue3 setup 函数使用, 调用一次就可以得好路由对象, 替代以前的 this.$router
import { useRouter } from 'vue-router'
const router = useRouter()
// 表单数据
const mobile = ref('13230000001')
const password = ref('')
const agree = ref(false)
const code = ref('')

// 登录逻辑
const login = async () => {
  console.log('校验成功')
  // 这是 submit 事件, 表单校验成功才会执行
  // 还有一个校验要补上, 确认用户已经同意条款
  if (!agree.value) {
    showToast('请先同意用户协议')
    return
  }
  console.log('这里才真的要登录')
  // 发请求
  // 根据当前表单显示情况, 决定发送哪个请求
  const res = isPass.value
    ? await loginByPassword(mobile.value, password.value)
    : await loginByMobile(mobile.value, code.value)

  console.log(res.data)
  // 存 pinia 仓库
  const store = useUserStore()
  store.setUser(res.data)
  // 提示用户
  showSuccessToast('登录成功')
  // 跳转页面
  router.push('/user')
}

// 登录方式切换
const isPass = ref(true)

// 获取 form 表单 dom
const form = ref<FormInstance>()
// 定义计时器
// 和计时器Id
let time = ref(0)
let timeId: number
// 获取验证码
const send = async () => {
  // 加上时间限制, 如果当前正在倒计时, 直接返回, 不做任何处理
  if (time.value > 0) {
    return
  }
  // 验证用户已经填上手机号
  await form.value?.validate('mobile')

  // 点击发送验证码按钮会触发
  const res = await sendMobileCode(mobile.value, 'login')
  console.log(res.data)

  // 初始化60秒
  time.value = 60
  // 设置定时器获取id
  timeId = window.setInterval(() => {
    time.value--
    // 如果已经减到0, 清理当前定时器
    if (time.value <= 0) {
      // 如果已经数够六十秒, 清理当前定时器
      window.clearInterval(timeId)
    }
  }, 1000)
}

// 每当跳出页面时, 记得清理定时器
onUnmounted(() => {
  window.clearInterval(timeId)
})

// 密码是否可见
const isShow = ref(false)
</script>

<template>
  <div class="login-page">
    <!-- 顶部导航 -->
    <cp-nav-bar
      right-text="注册"
      @click-right="$router.push('/register')"
    ></cp-nav-bar>
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ isPass ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <van-form ref="form" autocomplete="off" @submit="login">
      <van-field
        name="mobile"
        v-model="mobile"
        :rules="mobileRules"
        placeholder="请输入手机号"
        type="tel"
      ></van-field>
      <van-field
        v-if="isPass"
        v-model="password"
        :rules="passwordRules"
        placeholder="请输入密码"
        :type="isShow ? 'text' : 'password'"
      >
        <template #button>
          <cp-icons
            @click="isShow = !isShow"
            :name="isShow ? 'login-eye-on' : 'login-eye-off'"
          />
        </template>
      </van-field>
      <van-field
        v-else
        v-model="code"
        :rules="codeRules"
        placeholder="短信验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit">
          登 录
        </van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
